package com.tfswx.ocrengine.executor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tfswx.ocrengine.dto.OcrOutputDTO;
import com.tfswx.ocrengine.exception.AppException;
import com.tfswx.ocrengine.util.HttpUtil;
import com.tfswx.ocrengine.util.XunfeiOcrUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Ricky
 * @date 2021/1/11
 */
public class XunfeiOcrExecutor extends AbstractOcrExecutor {

    @Override
    public OcrOutputDTO run(String wjnr) throws EngineException {
        String url = "http://" + getHost() + "/tuling/ocr/v2/base64/param";
        Map<String, Object> param = new HashMap<>();
        param.put("trackId", System.currentTimeMillis());
        param.put("base64", wjnr);
        Map<String, String> p = new HashMap<>();
        p.put("pagetype", "page");
        // 朝向检测 od
        p.put("funclist", "ocr");
        p.put("resultlevel", "3");
        param.put("params", JSON.toJSONString(p));

        JSONObject response;
        try {
            response = HttpUtil.postForObject(url, param, JSONObject.class);
        } catch (Exception e) {
            throw new EngineException("引擎调用失败：" + e.getMessage(), e);
        }
        JSONObject stateJsonObj = response.getJSONObject("state");
        int code = stateJsonObj.getIntValue("code");
        boolean success = stateJsonObj.getBooleanValue("success");
        int ok = stateJsonObj.getIntValue("ok");
        JSONObject bodyJsonObj = response.getJSONObject("body");
        if (code == 0 && success && ok == 1) {
            // 识别成功
            if (bodyJsonObj == null) {
                throw new AppException("识别结果为空");
            }
            JSONObject data = XunfeiOcrUtils.convert2Ali(response);

            return data.toJavaObject(OcrOutputDTO.class);
        }
        throw new AppException(stateJsonObj.getString("failed"));
    }
}
